<script setup lang="ts">
/**
 * @description 一个通用的列表形式的“项目详情”页面，使用这个页面的角色有“业务员”和“地区经理”。
 * 对于“业务员”，这个页面用于查看项目的审核详情。
 * 对于“地区经理”，这个页面用于查看待审批或已审批完成的项目的审核详情。
 */

import dayjs from 'dayjs'
import { fetchProjectDetailAPI } from '@/apis/fetchProjectDetail'
import { fetchProjectPaymentListAPI } from '@/apis/fetchProjectPaymentList'
import { verifyProjectAPI } from '@/apis/verifyProject'
import { useProjectConfigStore } from '@/store/projectConfig'
import { useUserInfoStore } from '@/store/userInfo'

// Assets
import pendingIcon from '@/static/images/review-pending.png'
import successIcon from '@/static/images/review-success.png'
import modalRejectIcon from '@/static/images/modal/reject.png'

const router = useRouter()
const userInfoStore = useUserInfoStore()
const projectConfigStore = useProjectConfigStore()

const projectId = ref('')

// 项目
const project = ref<Project | null>(null)
// 打款列表
const payList = ref<Payment[]>([])

// 合同照片
const contactImages = computed(() => {
  if (project.value?.contract_images)
    return project.value.contract_images.split(',')
  else
    return []
})

// 首次打款的信息
const payment = computed(() => {
  if (payList.value.length === 0)
    return
  return {
    payTime: dayjs.unix(payList.value[0].create_time!).format('YYYY-MM-DD HH:mm:ss'),
    payDesc: payList.value[0].pay_desc as string,
    payImages: (payList.value[0].pay_images as string).split(','),
    payMoney: payList.value[0].pay_money,
  }
})

onLoad(async (options) => {
  if (options && options.project_id)
    projectId.value = options.project_id
})

onShow(async () => {
  try {
    const projRes = await fetchProjectDetailAPI(`${projectId.value}`, userInfoStore.userInfo!.token!)
    if (projRes.data?.code === 1)
      project.value = projRes.data.data
    else
      uni.showToast({ title: projRes.data?.msg, icon: 'none' })
    const payListRes = await fetchProjectPaymentListAPI(`${projectId.value}`, userInfoStore.userInfo!.token!)
    if (payListRes.data?.code === 1)
      payList.value = payListRes.data.data
    else
      uni.showToast({ title: payListRes.data?.msg, icon: 'none' })
  }
  catch (err) {
    uni.showToast({ title: '获取数据失败，请稍后重试', icon: 'none' })
  }
})

/* --------------------------- 业务员、地区经理 Part START -------------------------- */
// 项目审核状态名称
const verifyName = computed(() => {
  if (project.value)
    return projectConfigStore.projectVerifyStatusStr[project.value.verify!]
})

// 项目审核状态图标
const verifyIcon = computed(() => {
  if (verifyName.value === '待审核')
    return pendingIcon
  else
    return successIcon
})

// 项目审核状态说明
const verifyDescription = computed(() => {
  if (userInfoStore.belongTo(['4'])) {
    if (verifyName.value === '待审核')
      return '您的新建项目提交成功，请耐心等待地区经理审核...'
    else if (verifyName.value === '审核通过')
      return '您的新建项目审核通过'
    else
      return '您的新建项目审核驳回，请按照下方原因修改：'
  }
  else if (userInfoStore.belongTo(['1'])) {
    if (verifyName.value === '待审核')
      return '请审核业务员提交的新建项目申请'
    else if (verifyName.value === '审核通过')
      return '您已审核通过业务员新建项目的申请'
    else if (verifyName.value === '审核驳回')
      return '此新建项目申请已经审核驳回，驳回原因如下：'
  }
})
/* ---------------------------- 业务员、地区经理 Part END --------------------------- */

/* ----------------------------- 业务员 Part START ----------------------------- */
/**
 * @description 处理重新提交录入项目的事件
 */
function handleResubmit() {
  router.replace({
    name: 'createProject',
    params: {
      project_id: project.value!.id!.toString(),
      payment: JSON.stringify(payment.value),
    },
  })
}
/* ------------------------------ 业务员 Part END ------------------------------ */

/* ----------------------------- 地区经理 Part START ---------------------------- */
// 是否显示审核驳回弹窗
const isShowRejectModal = ref(false)
// 对某个项目执行通过或驳回操作时，将 id 暂存到这里
const tempProjectId = ref('')
// 驳回原因
const reason = ref({
  text: '',
})

/**
 * @description 处理审核驳回事件
 *
 * @param projectId - 驳回的项目的 id
 */
function handleReject(projectId: string) {
  tempProjectId.value = projectId
  isShowRejectModal.value = true
}

/**
 * @description 处理确定驳回项目事件
 */
async function handleConfirmReject() {
  if (reason.value.text) {
    try {
      const res = await verifyProjectAPI({
        project_id: tempProjectId.value,
        verify: '3',
        verify_desc: reason.value.text,
      }, userInfoStore.userInfo!.token!)
      if (res.data?.code === 1)
        router.back()
      else
        uni.showToast({ title: res.data?.msg, icon: 'none' })
    }
    catch (error) {
      uni.showToast({ title: '驳回失败', icon: 'none' })
    }
    isShowRejectModal.value = false
    tempProjectId.value = ''
  }
  else {
    uni.showToast({ title: '请输入驳回原因', icon: 'none' })
  }
}

/**
 * @description 处理取消驳回项目事件
 */
function handleCancelReject() {
  isShowRejectModal.value = false
  tempProjectId.value = ''
  reason.value.text = ''
}

/**
 * @description 处理审批通过项目事件
 *
 * @param projectId - 审批通过的项目的 id
 */
function handleAgree(projectId: string) {
  router.push({
    name: 'assignForeman',
    params: {
      project_id: projectId,
      is_initial: 'true',
    },
  })
}
/* ------------------------------ 地区经理 Part END ----------------------------- */
</script>

<template>
  <Spacer height="30" />
  <view class="flex flex-col">
    <view v-if="verifyName === '待审核' || verifyName === '审核通过'" class="flex items-center text-30rpx leading-30rpx font-bold text-secondary">
      <image class="w-60rpx h-60rpx" :src="verifyIcon" />
      {{ verifyName }}
    </view>
    <view class="text-28rpx leading-28rpx text-secondary">
      {{ verifyDescription }}
    </view>
    <view v-if="verifyName === '审核驳回'" class="px-30rpx py-20rpx mt-30rpx text-28rpx leading-48rpx text-secondary bg-#FFF2F2 rounded-10rpx">
      {{ project?.verify_desc ? project?.verify_desc : '无' }}
    </view>
  </view>
  <Spacer height="10" />
  <view class="flex items-center pt-30rpx pb-24rpx">
    <image class="w-36rpx h-32rpx mr-13rpx" src="@/static/images/folder.png" />
    <view class="text-30rpx leading-30rpx font-bold text-secondary">
      项目信息
    </view>
  </view>
  <view class="bg-white rounded-10rpx">
    <ListCell label="项目名称">
      <ListValue>{{ project?.name || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="项目定位">
      <ListValue>{{ `${project?.province}${project?.city}${project?.district}` }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="详细位置">
      <ListValue>{{ project?.address || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="装修面积">
      <ListValue>{{ project?.extent || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="装修风格">
      <ListValue>{{ project?.zx_style || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="装修类型">
      <ListValue>{{ project?.project_type_name || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="工期截止">
      <ListValue>{{ project?.duration ? dayjs.unix(Number(project?.duration)).format('YYYY.MM.DD') : '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="户型">
      <ListValue>{{ project?.house_type_name || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="项目总价">
      <ListValue>{{ project?.money_total || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell direction="column" label="项目合同照片">
      <PictureGrid mode="display" :width="630" :cols="3" :pictures="contactImages" />
    </ListCell>
    <Divider />
    <ListCell direction="column" label="具体要求">
      <ListParagraph>{{ project?.ask || '未知' }}</ListParagraph>
    </ListCell>
    <Divider />
    <ListCell label="是否带家具">
      <view class="flex items-center h-116rpx text-#333333 text-28rpx leading-28rpx font-medium">
        <view class="flex items-center">
          <Checkbox :checked="Boolean(project?.is_furniture)" />
          <Spacer width="12" />
          <view>是</view>
        </view>
        <Spacer width="56" />
        <view class="flex items-center">
          <Checkbox :checked="!Boolean(project?.is_furniture)" />
          <Spacer width="12" />
          <view>否</view>
        </view>
      </view>
    </ListCell>
    <Divider />
    <ListCell label="是否带家电">
      <view class="flex items-center h-116rpx text-#333333 text-28rpx leading-28rpx font-medium">
        <view class="flex items-center">
          <Checkbox :checked="Boolean(project?.is_appliance)" />
          <Spacer width="12" />
          <view>是</view>
        </view>
        <Spacer width="56" />
        <view class="flex items-center">
          <Checkbox :checked="!Boolean(project?.is_appliance)" />
          <Spacer width="12" />
          <view>否</view>
        </view>
      </view>
    </ListCell>
  </view>
  <view class="flex items-center pt-30rpx pb-24rpx">
    <image class="w-32rpx h-32rpx mr-13rpx" src="@/static/images/person.png" />
    <view class="text-30rpx leading-30rpx font-bold text-secondary">
      客户信息
    </view>
  </view>
  <view class="bg-white rounded-10rpx">
    <ListCell label="客户姓名">
      <ListValue>{{ project?.contacts_name || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="客户手机号">
      <ListValue>{{ project?.contacts_mobile || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell direction="column" label="打款信息">
      <PictureGrid mode="display" :width="630" :cols="3" :pictures="payment ? payment?.payImages : []" />
    </ListCell>
    <Divider />
    <ListCell label="打款时间">
      <ListValue>{{ payment?.payTime || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="打款金额">
      <ListValue>{{ payment?.payMoney ? `¥${payment?.payMoney}` : '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell direction="column" label="打款备注">
      <ListParagraph>{{ payment?.payDesc || '未知' }}</ListParagraph>
    </ListCell>
  </view>
  <view class="flex items-center pt-30rpx pb-24rpx">
    <image class="w-32rpx h-35rpx mr-13rpx" src="@/static/images/pen.png" />
    <view class="text-30rpx leading-30rpx font-bold text-secondary">
      录入信息
    </view>
  </view>
  <view class="bg-white rounded-10rpx">
    <ListCell label="业务员">
      <ListValue>{{ project?.salesman?.nickname || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="业务员手机号">
      <ListValue>{{ project?.salesman?.mobile || '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="提交时间">
      <ListValue>
        {{ project?.create_time ? dayjs.unix(project.create_time).format('YYYY-MM-DD HH:mm:ss') : '未知' }}
      </ListValue>
    </ListCell>
  </view>
  <view v-if="verifyName !== '待审核'" class="flex items-center pt-30rpx pb-24rpx">
    <image class="w-27rpx h-33rpx mr-13rpx" src="@/static/images/verify.png" />
    <view class="text-30rpx leading-30rpx font-bold text-secondary">
      审核信息
    </view>
  </view>
  <view v-if="verifyName !== '待审核'" class="bg-white rounded-10rpx">
    <ListCell label="审核人">
      <ListValue>{{ project?.manage?.nickname ? project?.manage?.nickname : '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="审核人手机号">
      <ListValue>{{ project?.manage?.mobile ? project.manage.mobile : '未知' }}</ListValue>
    </ListCell>
    <Divider />
    <ListCell label="审核时间">
      <ListValue>
        {{ project?.verify_time ? dayjs.unix(project.verify_time).format('YYYY-MM-DD HH:mm:ss') : '' }}
      </ListValue>
    </ListCell>
  </view>
  <Spacer height="240" />

  <!-- 业务员 & 项目被驳回 -->
  <RGButton
    v-if="userInfoStore.belongTo(['4']) && verifyName === '审核驳回'"
    class="fixed bottom-80rpx x-center"
    @tap="handleResubmit"
  >
    重新提交
  </RGButton>

  <!-- 地区经理 && 项目待审核 -->
  <view
    v-if="userInfoStore.belongTo(['1']) && verifyName === '待审核'"
    class="fixed bottom-80rpx x-center flex justify-between items-center w-750rpx px-30rpx"
  >
    <RGButton
      type="secondary"
      width="280"
      @tap="handleReject(`${project?.id}`)"
    >
      审核驳回
    </RGButton>
    <RGButton
      type="primary"
      width="392"
      @tap="handleAgree(`${project?.id}`)"
    >
      审核通过
    </RGButton>
  </view>

  <view>
    <!-- 审核拒绝的弹窗 -->
    <uv-overlay :show="isShowRejectModal" @tap="isShowRejectModal">
      <uv-transition mode="zoom-in" :show="isShowRejectModal">
        <view class="relative w-screen h-screen">
          <JZTModal :icon="modalRejectIcon">
            <view class="flex flex-col items-center">
              <Spacer height="146" />
              <view class="text-34rpx leading-34rpx font-bold text-primary">
                确认审核驳回吗？
              </view>
              <Spacer height="42" />
              <view class="w-606rpx">
                <view class="text-28rpx leading-28rpx text-secondary">
                  驳回原因
                </view>
                <Spacer height="30" />
                <TextAreaWrapper :modal-value="reason.text" placeholder="请输入驳回原因" @update:modal-value="(e) => reason.text = e" />
              </view>
              <Spacer height="52" />
              <view class="flex justify-between items-center w-590rpx h-100rpx">
                <view
                  class="flex justify-center items-center w-280rpx h-100rpx text-32rpx leading-32rpx text-#FF6D0A font-bold bg-white border-1px border-solid border-#FF6D0A rounded-full"
                  @tap.stop="handleCancelReject"
                >
                  取消
                </view>
                <view
                  class="flex justify-center items-center w-280rpx h-100rpx text-32rpx leading-32rpx text-white font-bold bg-brand rounded-full"
                  @tap.stop="handleConfirmReject"
                >
                  确定
                </view>
              </view>
              <Spacer height="60" />
            </view>
          </JZTModal>
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
</template>

<route lang="yaml">
name: 'verifyDetail'
style:
  navigationBarTitleText: '项目详情'
</route>
